<template>
  <!--Begin Login Begin-->
  <div class="log_bg">  
    <div class="top">
      <div class="logo"><router-link to="/"><img src="@/assets/images/logo.png" /></router-link></div>
    </div>
    <div class="regist">
      <div class="log_img"><img src="@/assets/images/l_img.png" width="611" height="425" /></div>
      <div class="reg_c">
        <form @submit.prevent="handleRegister">
          <table border="0" style="width:420px; font-size:14px; margin-top:20px;" cellspacing="0" cellpadding="0">
            <tbody>
              <tr height="50" valign="top">
                <td width="95">&nbsp;</td>
                <td>
                  <span class="fl" style="font-size:24px;">注册</span>
                  <span class="fr">已有商城账号，<router-link to="/login" style="color:#ff4e00;">我要登录</router-link></span>
                </td>
              </tr>
              <tr height="50">
                <td align="right"><font color="#ff4e00">*</font>&nbsp;用户名 &nbsp;</td>
                <td><input type="text" v-model="registerData.username" @input="onUsernameInput" class="l_user" /></td>
              </tr>
              <tr height="50">
                <td align="right"><font color="#ff4e00">*</font>&nbsp;密码 &nbsp;</td>
                <td><input type="password" v-model="registerData.password" class="l_pwd" /></td>
              </tr>
              <tr height="50">
                <td align="right"><font color="#ff4e00">*</font>&nbsp;确认密码 &nbsp;</td>
                <td><input type="password" v-model="registerData.confirmPassword" class="l_pwd" /></td>
              </tr>
              <tr height="50">
                <td align="right"><font color="#ff4e00">*</font>&nbsp;邮箱 &nbsp;</td>
                <td><input type="text" v-model="registerData.email" class="l_email" /></td>
              </tr>
              <tr height="50">
                <td align="right"><font color="#ff4e00">*</font>&nbsp;手机 &nbsp;</td>
                <td><input type="text" v-model="registerData.phone" class="l_tel" /></td>
              </tr>
              <tr height="50">
                <td align="right">邀请人会员名 &nbsp;</td>
                <td><input type="text" v-model="registerData.inviterName" class="l_mem" /></td>
              </tr>
              <tr height="50">
                <td align="right">邀请人ID号 &nbsp;</td>
                <td><input type="text" v-model="registerData.inviterId" class="l_num" /></td>
              </tr>
              <tr height="50">
                <td align="right"> <font color="#ff4e00">*</font>&nbsp;验证码 &nbsp;</td>
                <td>
                  <input type="text" v-model="registerData.captcha" class="l_ipt" style="width: 100px;" />
                  <img 
                    :src="captchaUrl" 
                    alt="图形验证码" 
                    class="captcha-image" 
                    @click="refreshCaptcha" 
                    title="点击刷新验证码"
                    style="vertical-align: middle; margin-left: 10px; cursor: pointer; height: 40px;"
                  />
                </td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td style="font-size:12px; padding-top:20px;">
                  <span style="font-family:'宋体';" class="fl">
                    <label class="r_rad"><input type="checkbox" v-model="registerData.agreeTerms" /></label><label class="r_txt">我已阅读并接受《用户协议》</label>
                  </span>
                </td>
              </tr>
              <tr height="60">
                <td>&nbsp;</td>
                <td><input type="submit" :value="loading ? '注册中...' : '立即注册'" class="log_btn" :disabled="loading" /></td>
              </tr>
            </tbody>
          </table>
        </form>
      </div>
    </div>
  </div>
  <!--End Login End--> 
</template>

<script>
import { register, getImageCaptcha } from '@/api/userApi'

export default {
  name: 'RegisterPage',
  data() {
    return {
      registerData: {
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
        phone: '',
        inviterName: '',
        inviterId: '',
        captcha: '',
        agreeTerms: false
      },
      loading: false,
      captchaUrl: ''
    }
  },
  mounted() {
    // 页面加载时自动生成验证码，使用固定key
    this.generateCaptcha();
  },
  beforeUnmount() {
    // 不再需要清理验证码定时器
  },
  methods: {
    generateCaptcha() {
      // 使用用户名作为key生成验证码，如果用户名为空则使用默认key
      const key = this.registerData.username && this.registerData.username.trim() !== '' ? 
                  this.registerData.username : 'register_captcha';
      this.captchaUrl = `/api/captcha/image?key=${encodeURIComponent(key)}&t=${new Date().getTime()}`;
    },
    
    refreshCaptcha() {
      // 手动刷新验证码
      this.generateCaptcha();
    },
    
    onUsernameInput() {
      // 用户名输入时不再刷新验证码
    },
    
    async handleRegister() {
      // 基本验证
      if (!this.registerData.username.trim()) {
        this.$message.error('请输入用户名')
        return
      }
      if (!this.registerData.password.trim()) {
        this.$message.error('请输入密码')
        return
      }
      if (this.registerData.password !== this.registerData.confirmPassword) {
        this.$message.error('两次输入的密码不一致')
        return
      }
      if (!this.registerData.email.trim()) {
        this.$message.error('请输入邮箱')
        return
      }
      if (!this.registerData.phone.trim()) {
        this.$message.error('请输入手机号')
        return
      }
      if (!this.registerData.captcha.trim()) {
        this.$message.error('请输入验证码')
        return
      }
      if (!this.registerData.agreeTerms) {
        this.$message.error('请先同意用户协议')
        return
      }
      
      // 邮箱格式验证
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(this.registerData.email)) {
        this.$message.error('请输入正确的邮箱格式')
        return
      }
      
      // 手机号格式验证
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(this.registerData.phone)) {
        this.$message.error('请输入正确的手机号')
        return
      }
      
      this.loading = true
      
      try {
        // 调用真实的注册API
        const registerParams = {
          username: this.registerData.username.trim(),
          password: this.registerData.password,
          phone: this.registerData.phone.trim(),
          email: this.registerData.email.trim(),
          captcha: this.registerData.captcha.trim(),
          captchaKey: this.registerData.username.trim()  // 使用用户名作为验证码key
        }
        
        const res = await register(registerParams)
        
        console.log('注册响应:', res)
        
        // 根据后端实际响应结构调整处理逻辑
        // 后端register接口直接返回User对象表示成功，返回异常表示失败
        const isSuccess = res && res.id !== undefined && res.id !== null
        
        if (isSuccess) {
          this.$message.success('注册成功！')
          // 跳转到登录页面
          this.$router.push('/login')
        } else {
          // 尝试从响应中获取错误信息
          let errorMessage = '注册失败'
          if (res && res.message) {
            errorMessage = res.message
          } else if (res && res.msg) {
            errorMessage = res.msg
          } else if (typeof res === 'string') {
            errorMessage = res
          }
          this.$message.error(errorMessage || '注册失败')
          // 注册失败时刷新验证码
          this.refreshCaptcha()
        }
      } catch (error) {
        console.error('注册错误:', error)
        this.$message.error('注册失败，请稍后重试')
        // 注册失败时刷新验证码
        this.refreshCaptcha()
      } finally {
        this.loading = false
      }
    },
    
    refreshCaptcha() {
      // 只有当用户名不为空时才刷新验证码
      if (this.registerData.username && this.registerData.username.trim() !== '') {
        const key = this.registerData.username;
        this.captchaUrl = `/api/captcha/image?key=${encodeURIComponent(key)}&t=${new Date().getTime()}`;
      } else {
        // 用户名为空时清空验证码URL
        this.captchaUrl = '';
      }
    }
  }
}
</script>

<style scoped>
/* 完全按照原始HTML页面的样式结构 */

/* Header 部分 */
.soubg {
  background: #f5f5f5;
  height: 35px;
  line-height: 35px;
}

.sou {
  width: 1200px;
  margin: 0 auto;
  font-size: 12px;
}

.sou .fr {
  float: right;
}

.sou .fl {
  float: left;
}

.sou a {
  color: #666;
  text-decoration: none;
}

.sou a:hover {
  color: #ff4e00;
}

.s_sh {
  margin: 0 10px;
}

.sh1, .sh2 {
  display: inline-block;
  width: 16px;
  height: 16px;
  text-indent: -9999px;
  margin-right: 5px;
}

.sh1 {
  background: url('@/assets/images/sh1.png') no-repeat;
  background-size: 16px 16px;
}

.sh2 {
  background: url('@/assets/images/sh2.png') no-repeat;
  background-size: 16px 16px;
}

/* 登录区域 */
.log_bg {
  background: #fff;
  min-height: 600px;
}

.top {
  width: 1200px;
  margin: 0 auto;
  padding: 30px 0;
}

.logo img {
  height: 60px;
}

.regist {
  width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: flex-start;
  gap: 50px;
}

.log_img {
  flex-shrink: 0;
}

.reg_c {
  flex: 1;
  max-width: 470px;
}

.reg_c table {
  width: 100%;
}

.reg_c td {
  vertical-align: middle;
}

.l_user, .l_pwd, .l_email, .l_tel, .l_mem, .l_num, .l_ipt {
  width: 100%;
  height: 40px;
  border: 1px solid #ddd;
  padding: 0 10px;
  font-size: 14px;
  box-sizing: border-box;
}

.l_user:focus, .l_pwd:focus, .l_email:focus, .l_tel:focus, .l_mem:focus, .l_num:focus, .l_ipt:focus {
  border-color: #ff4e00;
  outline: none;
}

.l_ipt {
  width: 120px;
  display: inline-block;
  vertical-align: middle;
  margin-right: 10px;
}

.r_rad {
  margin-right: 5px;
}

.r_txt {
  color: #666;
}

.log_btn {
  width: 100%;
  height: 45px;
  background: #ff4e00;
  color: white;
  border: none;
  font-size: 16px;
  cursor: pointer;
  border-radius: 3px;
}

.log_btn:hover {
  background: #e6440a;
}

.log_btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* Footer 部分 */
.btmbg {
  background: #f5f5f5;
  padding: 30px 0;
  text-align: center;
  color: #999;
  font-size: 12px;
  margin-top: 50px;
}

.btm {
  width: 1200px;
  margin: 0 auto;
  line-height: 20px;
}

.btm img {
  margin: 10px 2px 0;
  vertical-align: top;
}

/* 清除浮动 */
.sou:after,
.top:after,
.regist:after {
  content: "";
  display: table;
  clear: both;
}
</style>